package com.qupai.lib_base.utils

import android.annotation.SuppressLint
import android.content.Context
import android.media.MediaScannerConnection
import android.os.Environment
import android.webkit.MimeTypeMap
import android.widget.ImageView
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.qupai.lib_base.app.BaseApplication
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

/**
 * Created by 18369 on 2018/8/13.
 * Time： 16:59
 * ClassNote：
 */
object GlideLoadPictureUtils {
    @JvmStatic
    fun loadPicture(path: Any?, imageView: ImageView?) {
        if (ObjectUtils.isEmpty(path)) {
            return
        }
        val requestOptions = RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
        Glide.with(BaseApplication.psaApp).load(path).apply(requestOptions).into(imageView!!)
    }

    fun loadNoCachePicture(path: Any?, imageView: ImageView?) {
        if (ObjectUtils.isEmpty(path)) {
            return
        }
        val requestOptions = RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.NONE)
        Glide.with(BaseApplication.psaApp).load(path).apply(requestOptions).into(imageView!!)
    }
    //    public static void loadPicture(Context context, Object path, ImageView imageView, int corner, GlideRoundedCornersTransform.CornerType cornerType) {
    //        RequestOptions requestOptions = new RequestOptions()
    //            .transform(new GlideRoundedCornersTransform(corner, cornerType))
    //            .diskCacheStrategy(DiskCacheStrategy.ALL);
    //        Glide.with(context).load(path).apply(requestOptions).into(imageView);
    //    }
    //
    //    public static void loadUserHead(Context context, Object path, ImageView imageView) {
    //        RequestOptions options = new RequestOptions()
    //            .circleCrop()
    //            .placeholder(R.drawable.default_tx)
    //            .error(R.drawable.default_tx)
    //            .diskCacheStrategy(DiskCacheStrategy.NONE);
    //        Glide.with(context).load(path).apply(options).into(imageView);
    //    }
    /**
     * 保存图片到目录
     *
     * @param context Activity
     * @param imgUrl  imgUrl
     */
    @SuppressLint("CheckResult")
    fun saveImgToGallery(context: Context?, imgUrl: String?, floder: String) {
        Observable.create(ObservableOnSubscribe { emitter: ObservableEmitter<File?> ->
            //Glide提供了一个download() 接口来获取缓存的图片文件，
            // 但是前提必须要设置diskCacheStrategy方法的缓存策略为
            // DiskCacheStrategy.ALL或者DiskCacheStrategy.SOURCE，
            // 还有download()方法需要在子线程里进行
            val file = Glide.with(context!!)
                .download(imgUrl)
                .submit()
                .get()
            val fileParentPath = Environment.getExternalStorageDirectory().absolutePath + "/" +  /*Configuration.PROJECT_WORD +*/floder
            val appDir = File(fileParentPath)
            if (!appDir.exists()) {
                appDir.mkdirs()
            }
            //获得原文件流
            val fis = FileInputStream(file)
            //保存的文件名
            val fileName =  /*Configuration.PROJECT_WORD +*/"_" + System.currentTimeMillis() + ".jpg"
            //目标文件
            val targetFile = File(appDir, fileName)
            //输出文件流
            val fos = FileOutputStream(targetFile)
            // 缓冲数组
            val b = ByteArray(1024 * 8)
            while (fis.read(b) != -1) {
                fos.write(b)
            }
            fos.flush()
            fis.close()
            fos.close()
            //扫描媒体库
            val extension = MimeTypeMap.getFileExtensionFromUrl(targetFile.absolutePath)
            val mimeTypes = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
            MediaScannerConnection.scanFile(context, arrayOf(targetFile.absolutePath), arrayOf(mimeTypes), null)
            emitter.onNext(targetFile)
        }) //发送事件在io线程
            .subscribeOn(Schedulers.io()) //最后切换主线程提示结果
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { file: File? -> ToastUtils.showShort("保存图片成功") }
            ) { throwable: Throwable? -> ToastUtils.showShort("保存失败") }
    }
}